import 'dart:io';

import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:qrcode/qrcode.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with TickerProviderStateMixin {
  QRCaptureController _captureController = QRCaptureController();
  String imagePath;

  bool _isTorchOn = false;

  String _captureText = '';
  int count = 0;

  double x = 0;
  double y = 0;
  double w = 10;
  double h = 10;

  @override
  void initState() {
    super.initState();

    _captureController.onCapture((data) {

      double _x = data['y'];
      double _y = data['x'];
      double _w = data['w'];
      double _h = data['h'];
      print('x:'+_x.toString()+" ,y:"+_y.toString()+' ,w:'+_w.toString()+" ,h:"+_h.toString());
      if(_x != null && _y != null){
        if(_y <= 0){
          _y = 0;
        }
        if(_x <= 0){
          _x = 0;
        }

        _x = (_w/2)+_x;
        _y = (_h/2)+_y;
        setState(() {
          x = 300*_x;

          y = 300*_y;

          // w = 300*_w;
          //
          // h = 300*_h;


        });
      }


    });


  }

  @override
  void dispose() {

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('扫一扫'),
        ),
        body: Stack(
          alignment: Alignment.center,
          children: <Widget>[
            Container(

              child: QRCaptureView(
              controller: _captureController,
            ),
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: _buildToolBar(),
            ),
            Container(
              child: Text('$_captureText'),
            ),



            Container(
              alignment: Alignment.topRight,
              child: imagePath != null ? Image.file(File(imagePath),width: 100,):Container(),
            ),

            Container(
              width: 300,
              height: 300,
              alignment: Alignment.topLeft,
              padding: EdgeInsets.only(left: x,top: y),
              //color: Colors.orangeAccent.withAlpha(100),
              child: Container(
                width: w,
                height: h,
                color: Colors.redAccent.withAlpha(150),
              ),
            )


          ],
        ),
      ),
    );
  }



  Widget _buildToolBar() {
    return Row(
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            FlatButton(
              onPressed: () {
                _captureController.pause();
              },
              child: Text('pause'),
            ),
            FlatButton(
              onPressed: () {
                if (_isTorchOn) {
                  _captureController.torchMode = CaptureTorchMode.off;
                } else {
                  _captureController.torchMode = CaptureTorchMode.on;
                }
                _isTorchOn = !_isTorchOn;
              },
              child: Text('torch'),
            ),
            FlatButton(
              onPressed: () {
                _captureController.resume();
              },
              child: Text('resume'),
            ),
            FlatButton(
              onPressed: () {
                //_captureController.takePicture("path").;
                takePicture().then((value){
                  setState(() {
                    imagePath = value;
                  });

                  if(value != null){
                    print("照片路径:"+value);
                  }else{
                    print("拍照失败");
                  }
                  //if (filePath != null) showInSnackBar('Picture saved to $filePath');
                });
              },
              child: Text('拍照'),
            ),
          ],
        );
  }

  Future<String> takePicture() async {

    count++;
    final Directory extDir = await getApplicationDocumentsDirectory();
    final String dirPath = '${extDir.path}/Pictures/flutter_test';
    await Directory(dirPath).create(recursive: true);
    final String filePath = '$dirPath/${count}.jpg';


    await _captureController.takePicture(filePath);
    return filePath;
  }
}

class MyPainter extends CustomPainter{

  final double x;
  final double y;


  MyPainter({
    this.x,
    this.y,
});

  Paint _paint = Paint()
    ..color = Colors.amber //画笔颜色
    ..strokeCap = StrokeCap.round //画笔笔触类型
    ..isAntiAlias = true //是否启动抗锯齿
    ..strokeWidth = 15.0; //画笔的宽度

  @override
  void paint(Canvas canvas, Size size) {
    // 画个实心圆
    canvas.drawCircle(new Offset(x, y), 10, _paint);
  }


  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return null;
  }

}
